package pile.customer.config;

import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import pile.customer.entity.ResponseResult;

import java.util.List;
import java.util.stream.Collectors;

@RestControllerAdvice
public class GlobalExceptionHandler {
    //全局捕获验证器异常
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResponseResult handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        String message = allErrors.stream().map(s -> s.getDefaultMessage()).collect(Collectors.joining(";"));
        //只提示第一条错误信息
        String[] split = message.split(";");
        String mes="";
        if(split.length>0){
            mes=split[0];
        }else{
            mes="";
        }
        return new ResponseResult(201, mes, "");
    }

}
